//
//  XWLodingView.swift
//  XWSurSpeed
//
//  Created by hopemobi-1 on 2024/8/5.
//

import UIKit
import SVGAPlayer

class XWLodingView: UIView {
    private var container:UIView!
    private var XWSvgaPlayer: SVGAPlayer!
    @IBOutlet weak var XWSVGBackView: UIView!
    
    @IBOutlet weak var XWLoadingLabel: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        showUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}
extension XWLodingView:SVGAPlayerDelegate{
    private func showUI() {
        container = Bundle.main.loadNibNamed("XWLodingView", owner: self,options: nil)?.first as? UIView
        container.frame = bounds
        addSubview(container)
        XWSvgaPlayer = SVGAPlayer.init()
        XWSVGBackView.addSubview(XWSvgaPlayer)
        XWSvgaPlayer.snp.makeConstraints { make in
            make.top.equalTo(XWSVGBackView)
            make.left.equalTo(XWSVGBackView)
            make.right.equalTo(XWSVGBackView)
            make.bottom.equalTo(XWSVGBackView)
        }
        XWSvgaPlayer.loops = 1
        XWSvgaPlayer.delegate = self
        XWSvgaPlayer.clearsAfterStop = true
        let parser = SVGAParser.init()
        parser.parse(withNamed: "loading5s", in: nil) { [self] videoItem in
            XWSvgaPlayer.videoItem = videoItem
            XWSvgaPlayer.startAnimation()
            
        }
    }
    func svgaPlayer(_ player: SVGAPlayer!, didAnimatedToPercentage percentage: CGFloat) {
        let tempPercentage = String.init(format: "%.f", percentage*100)
        XWLoadingLabel.text = "Loading...(" + (tempPercentage) + "%)"
        if(percentage == 1.0){
            self.removeFromSuperview()
        }
    }
}
